package org.makcro.sms.services.chat.web.client.mvc;

import java.util.ArrayList;
import java.util.List;

import org.makcro.sms.services.chat.web.client.AppEvents.BulkEvents;
import org.makcro.sms.services.chat.web.client.Constants.EventData;
import org.makcro.sms.services.chat.web.client.Constants.Services;
import org.makcro.sms.services.chat.web.client.mvc.view.SendBulkView;
import org.makcro.sms.services.chat.web.client.services.message.BulkServiceAsync;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class SendBulkController extends Controller {

	private SendBulkView		sendBulkView;

	/**
	 * Service instance used to send bulk messages
	 */
	private BulkServiceAsync	bulkServiceAsync;

	public SendBulkController() {
		registerEventTypes( BulkEvents.SEND_BULK_REQUESTED );
		registerEventTypes( BulkEvents.BULK_MESSAGE_ABOUT_TO_BE_SENT );
		sendBulkView = new SendBulkView( this );

		bulkServiceAsync = Registry.get( Services.BULK_SERVICE );
	}

	@Override
	public void handleEvent(AppEvent event) {
		EventType type = event.getType();
		if (type == BulkEvents.SEND_BULK_REQUESTED) {
			onSendBulkRequested( event );
		}
		if (type == BulkEvents.BULK_MESSAGE_ABOUT_TO_BE_SENT) {
			onBulkMessageAboutToBeSent( event );
		}
	}

	/**
	 * 
	 * @param event
	 */
	private void onBulkMessageAboutToBeSent(AppEvent event) {
		// extract event metadata
		String bulkText = event.<String> getData( EventData.BULK_MESSAGE_TEXT );
		String receiver = event.<String> getData( EventData.BULK_RECEIVER );

		List<String> receivers = new ArrayList<String>();
		receivers.add( receiver );
		
		bulkServiceAsync.sendBulk( bulkText, "", receivers, new AsyncCallback<Integer>() {
			
			@Override
			public void onSuccess(Integer result) {
				onBulkMessageSent(result);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				System.out.println(caught);	
			}
		});
	}

	protected void onBulkMessageSent(Integer result) {
		
		if(result > 0){
			AppEvent appEvent = new AppEvent( BulkEvents.BULK_MESSAGES_SENT );
			appEvent.setData( result );
			forwardToView( sendBulkView, appEvent );
			
		}
		else {
			AppEvent event = new AppEvent( BulkEvents.BULK_SENDING_FAILED );
			event.setData( result );
			forwardToView( this.sendBulkView, event );
		}
		
	}

	private void onSendBulkRequested(AppEvent event) {
		forwardToView( sendBulkView, event );

	}

}
